package cn.juque.common.mail;

import cn.juque.common.constants.MessageEnum;
import cn.juque.common.exception.AppException;
import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @author juque
 * @version 1.0.0
 * <ul>
 *     <li>MailSslSocketFactory</li>
 * </ul>
 * @date 2023-03-27 09:22:30
 **/
@Slf4j
public class MailSslSocketFactory extends SSLSocketFactory {

    private final SSLSocketFactory sslSocketFactory;

    public MailSslSocketFactory() {
        try {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[]{new MailTrustManager()}, null);
            sslSocketFactory = sslcontext.getSocketFactory();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new AppException(MessageEnum.SYSTEM_ERROR.getCode(), "邮件配置初始化异常");
        }
    }

    @Override
    public String[] getDefaultCipherSuites() {
        return new String[0];
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return new String[0];
    }

    @Override
    public Socket createSocket(Socket socket, String s, int i, boolean b) throws IOException {
        return sslSocketFactory.createSocket(socket, s, i, b);
    }

    @Override
    public Socket createSocket(String s, int i) throws IOException {
        return sslSocketFactory.createSocket(s, i);
    }

    @Override
    public Socket createSocket(String s, int i, InetAddress inetAddress, int i1) throws IOException {
        return sslSocketFactory.createSocket(s, i, inetAddress, i1);
    }

    @Override
    public Socket createSocket(InetAddress inetAddress, int i) throws IOException {
        return sslSocketFactory.createSocket(inetAddress, i);
    }

    @Override
    public Socket createSocket(InetAddress inetAddress, int i, InetAddress inetAddress1, int i1) throws IOException {
        return sslSocketFactory.createSocket(inetAddress, i, inetAddress1, i1);
    }
}
